﻿using System.Text;

namespace FileCommon.Utils;

public class HashHelper
{
    public static String ComputeMD5(string fileName)
    {
        var hashMD5 = string.Empty;
        //检查文件是否存在，如果文件存在则进行计算，否则返回空值
        if (!File.Exists(fileName))
        {
            throw new Exception($"不存在文件{fileName}");
        } //结束计算

        using var fs =
            new FileStream(fileName, FileMode.Open, FileAccess.Read);
        //计算文件的MD5值
        var calculator = System.Security.Cryptography.MD5.Create();
        var buffer = calculator.ComputeHash(fs);
        calculator.Clear();
        //将字节数组转换成十六进制的字符串形式
        var stringBuilder = new StringBuilder();
        for (int i = 0; i < buffer.Length; i++)
        {
            stringBuilder.Append(buffer[i].ToString("x2"));
        }

        hashMD5 = stringBuilder.ToString();
        return hashMD5;
    }

    public static string ComputeMD5(FileStream fileStream)
    {
        var hashMD5 = string.Empty;
        //计算文件的MD5值
        var calculator = System.Security.Cryptography.MD5.Create();
        var buffer = calculator.ComputeHash(fileStream);
        calculator.Clear();
        //将字节数组转换成十六进制的字符串形式
        var stringBuilder = new StringBuilder();
        foreach (var t in buffer)
        {
            stringBuilder.Append(t.ToString("x2"));
        }

        hashMD5 = stringBuilder.ToString();
        return hashMD5;
    }
}